package controllers

import dao._
import play.api.mvc.{AbstractController, ControllerComponents}
import play.api.routing.JavaScriptReverseRouter
import tool.Tool

import java.io.File
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import implicits.Implicits._
import shared.pojo.Pojo._
import upickle.default._

import java.nio.file.Files

/**
 * Created by Administrator on 2019/8/7
 */
class ToolController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val userDao: UserDao,
  implicit val memberDao: MemberDao,
  implicit val companyMemberDao: CompanyMemberDao,
  implicit val specialMemberDao: SpecialMemberDao,
) extends
  AbstractController(cc) {

  def viewFile = Action { implicit request =>
    val data = Tool.transformRq.transform(reader[FilePathData])
    val file = new File(data.filePath)
    Ok.sendFile(file, onClose = () => {
      file.deleteOnExit()
    })
  }

  def uploadFile = Action(parse.multipartFormData) { implicit request =>
    val tmpDir = Tool.createTempDirectory("tmpDir")
    val file = Tool.fileMoveDir("file", tmpDir)
    val response = UploadFile.Response(valid = true, filePath = file.getAbsolutePath)
    Ok(writeJs(response))
  }

  def viewImage = Action { implicit request =>
    val queryMap = request.queryString.map { case (k, v) =>
      (k, v.head)
    }
    val data = writeJs(queryMap).transform(reader[ViewImage.Request])
    val ifModifiedSinceStr = request.headers.get(IF_MODIFIED_SINCE)
    val file = new File(Tool.getImagesDir(data.id), data.fileName)
    val lastModifiedStr = file.lastModified().toString
    val MimeType = "image/jpeg"
    val byteArray = Files.readAllBytes(file.toPath)
    if (ifModifiedSinceStr.isDefined && ifModifiedSinceStr.get == lastModifiedStr) {
      NotModified
    } else {
      Ok(byteArray).as(MimeType).withHeaders(LAST_MODIFIED -> file.lastModified().toString)
    }
  }


}
